<template>
  <div class="loginForm">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="loginRules"
      label-width="120px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
// @ is an alias to /src
import { reactive, ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

const store = useStore();
const router = useRouter();
const ruleFormRef = ref();
const ruleForm = reactive({
  username: '',
  password: '',
});
const loginRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      axios.post('/adminApi/user/login', ruleForm).then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: '登录成功',
            type: 'success',
          });
          store.commit('getUserInfo', res.data);
          router.push('/index');
        } else {
          ElMessage.error('用户名密码不匹配');
        }
      });
    } else {
      return false;
    }
  });
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style lang="scss">
.loginForm {
  background-color: aquamarine;
  width: 500px;
  height: 300px;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  form {
    margin: 5% 5% 0 0;
  }
}
</style>
